﻿using System;
using System.Collections.Generic;
using System.Text;

using BusinessLogic.BusinessRules;
using BusinessLogic.ClassFactory;
using Model;
using DataAccess;
using System.Text.RegularExpressions;
using System.Collections;
using System.Threading;

using Common;
namespace IssueCommon
{
    public class SectionIssue : IssueBase, IDisposable
    {
        private Sections _Section;
        public SectionIssue(int intSectionID, SessionUser sessionUser)
        {
            SessionUser = sessionUser;
            SectionsFactory objFactory = new SectionsFactory(_DBManager);
            this._Section = objFactory.Creator(intSectionID);
            this._Section.SessionUser = sessionUser;
            if (this._Section == null)
            {
                string strMsg = string.Format("没有找到ID为{0}的栏目！", intSectionID);
                throw new CustomException(strMsg);
            }
            base._intDefaultID = intSectionID;
            objFactory.Dispose();
        }
        public void DoSectionIssue(SessionUser objSessionUser)
        {
            //栏目停用，不发布
            if (_Section.DataItem.intState == (int)Utility.STState.NoUse)
            {
                return;
            }
            //栏目不显示，不发布
            if (_Section.DataItem.intDisplay == (int)Utility.STDisplay.No)
            {
                return;
            }


            //发布栏目首页
            CreateSectionIndex();

        }

        private void CreateSectionIndex()
        {
            //判断栏目是否有模板
            if (this._Section.DataItem.IsintSectionTemIDNull())
            {
                string strMsg = string.Format("ID为({0})名称是{1}的栏目没有找到模板！", this._Section.DataItem.intSectionID, this._Section.DataItem.chvSTCName);
                throw new CustomException(strMsg);
            }
            //读取模板内容
            string strTemplate = Template.GetTemplateString(this._Section.DataItem.intSectionTemID, base.SessionUser);

            // 解析模板插件的正则表达式
            // 找出不分页的插件
            string strRegexNoPage = string.Format("{0}(?!.+<pagesize>[0-9]+</pagesize>.+)([\\d\\D]+?){1}", Model.Common.Plugin.PluginBeginTag, Model.Common.Plugin.PluginEndTag);
            //解析模板中公共插件
            string strHtml = string.Empty;
            //if (AppConfig.GetIsShtml() == (int)Utility.IssueWebCodeLanguage.html)
            //{
            //    //并将模板文件中的公共插件替换，还原正常完整网页
            string strCommonRegexNoPage = string.Format("{0}([\\d\\D]+?){1}", Model.Common.Plugin.CommonPluginBeginTag, Model.Common.Plugin.CommonPluginEndTag);
            strHtml = Regex.Replace(strTemplate, strCommonRegexNoPage, new MatchEvaluator(base.ReplaceCommonPlugin), RegexOptions.IgnoreCase);
            strHtml = Regex.Replace(strHtml, strRegexNoPage, new MatchEvaluator(base.ReplacePlugin), RegexOptions.IgnoreCase);
            //}
            //else
            //{
            //    // 将模板文件中的插件部分用数据库中的真实数据替换
            //    strHtml = Regex.Replace(strTemplate, strRegexNoPage, new MatchEvaluator(base.ReplacePlugin), RegexOptions.IgnoreCase);
            //}

            // 找出需要分页的插件(一个模板只能有一个分页的插件)
            string strRegexHavePage = string.Format("{0}(?=.+<pagesize>[0-9]+</pagesize>.+)([\\d\\D]+?){1}", Model.Common.Plugin.PluginBeginTag, Model.Common.Plugin.PluginEndTag);
            Regex objRegex = new Regex(strRegexHavePage);
            if (objRegex.IsMatch(strHtml) == false)  // 无分页的插件
            {
                string strPath = "";
                if (base.SessionUser.EnableParentPath)
                {
                    string strParentPath = (this._Section.DataItem.IschvParentPathNull() ? "shtml\\" : (this._Section.DataItem.chvParentPath.Trim() == "" ? "shtml\\" : (this._Section.DataItem.chvParentPath.Trim() == "/" ? "" : this._Section.DataItem.chvParentPath + "\\")));

                    if (SessionUser.WebSiteLevel != 1)
                    {
                        strParentPath = SessionUser.VartualPath + "\\" + strParentPath;
                    }

                    if (!System.IO.Directory.Exists(SessionUser.IssuePath + strParentPath))
                    {
                        System.IO.Directory.CreateDirectory(SessionUser.IssuePath + strParentPath);
                    }
                    strPath = string.Format("{0}{1}{2}.{3}", base.SessionUser.IssuePath + strParentPath, this._Section.DataItem.IschvPageNameNull() ? "T-" + this._Section.DataItem.intSectionID : (string.IsNullOrEmpty(this._Section.DataItem.chvPageName.Trim()) ? "T-" + this._Section.DataItem.intSectionID : this._Section.DataItem.chvPageName),"", AppConfig.GetWebFileType());

                    strHtml = Htmlhandler.HandlerHtmlElementPath(strHtml, base.SessionUser);
                }
                else
                {
                    strPath = string.Format("{0}\\T-{1}.{2}", base.SessionUser.IssuePath + "\\shtml", this._Section.DataItem.intSectionID, AppConfig.GetWebFileType());
                }

                base.GenerateHtmlFile(strPath, strHtml);
            }
            else
            {
                strTemplate = strHtml;
                Match objMatch = objRegex.Match(strTemplate);


                string[] strSnippets = base.ParsePagesPlugin(objMatch.ToString(), false);
                if (strSnippets != null)
                {
                    int intIssuePages = Convert.ToInt32(AppConfig.GetSecctionIssuePages() ?? "-1");

                    string strPath = "";
                    if (base.SessionUser.EnableParentPath)
                    {
                        string strParentPath = (this._Section.DataItem.IschvParentPathNull() ? "shtml\\" : (this._Section.DataItem.chvParentPath.Trim() == "" ? "shtml\\" :  (this._Section.DataItem.chvParentPath.Trim() == "/" ?"": this._Section.DataItem.chvParentPath + "\\")));

                        if (SessionUser.WebSiteLevel != 1)
                        {
                            strParentPath = SessionUser.VartualPath + "\\" + strParentPath;
                        }

                        strPath = base.SessionUser.IssuePath + strParentPath;
                    }
                    else
                    {
                        strPath = base.SessionUser.IssuePath + "shtml";
                    }
                    for (int i = 0; i < strSnippets.Length; i++)
                    {
                        if (intIssuePages != -1 && i > intIssuePages)
                        {
                            break;
                        }
                        string strSnippet = strSnippets[i];
                        string strTmpHtml = objRegex.Replace(strTemplate, strSnippet);
                        string strFileName = string.Empty;   // 每页的文件名
                        if (i == 0)
                        {
                            if (base.SessionUser.EnableParentPath)
                            {
                                string strParentPath = (this._Section.DataItem.IschvParentPathNull() ? "shtml\\" : (this._Section.DataItem.chvParentPath.Trim() == "" ? "shtml\\" :  (this._Section.DataItem.chvParentPath.Trim() == "/" ?"": this._Section.DataItem.chvParentPath + "\\")));

                                if (SessionUser.WebSiteLevel != 1)
                                {
                                    strParentPath = SessionUser.VartualPath + "\\" + strParentPath;
                                }

                                if (!System.IO.Directory.Exists(SessionUser.IssuePath + strParentPath))
                                {
                                    System.IO.Directory.CreateDirectory(SessionUser.IssuePath + strParentPath);
                                }

                                strFileName = string.Format("{0}{1}.{2}", this._Section.DataItem.IschvPageNameNull() ? "T-" + this._Section.DataItem.intSectionID : (string.IsNullOrEmpty(this._Section.DataItem.chvPageName.Trim()) ? "T-" + this._Section.DataItem.intSectionID : this._Section.DataItem.chvPageName), "", AppConfig.GetWebFileType());

                                strTmpHtml = Htmlhandler.HandlerHtmlElementPath(strTmpHtml, base.SessionUser);
                            }
                            else
                            {
                                strFileName = string.Format("T-{0}.{1}", this._Section.DataItem.intSectionID, AppConfig.GetWebFileType());
                            }
                        }
                        else
                        {
                            if (base.SessionUser.EnableParentPath)
                            {
                                string strParentPath = (this._Section.DataItem.IschvParentPathNull() ? "shtml\\" : (this._Section.DataItem.chvParentPath.Trim() == "" ? "shtml\\" : (this._Section.DataItem.chvParentPath.Trim() == "/" ?"": this._Section.DataItem.chvParentPath + "\\")));

                                if (SessionUser.WebSiteLevel != 1)
                                {
                                    strParentPath = SessionUser.VartualPath + "\\" + strParentPath;
                                }

                                if (!System.IO.Directory.Exists(SessionUser.IssuePath + strParentPath))
                                {
                                    System.IO.Directory.CreateDirectory(SessionUser.IssuePath + strParentPath);
                                }

                                strFileName = string.Format("{0}{1}--{2}.{3}", this._Section.DataItem.IschvPageNameNull() ? "T-" + this._Section.DataItem.intSectionID : (string.IsNullOrEmpty(this._Section.DataItem.chvPageName.Trim()) ? "T-" + this._Section.DataItem.intSectionID : this._Section.DataItem.chvPageName), "", i, AppConfig.GetWebFileType());

                                strTmpHtml = Htmlhandler.HandlerHtmlElementPath(strTmpHtml, base.SessionUser);
                            }
                            else
                            {
                                strFileName = string.Format("T-{0}--{1}.{2}", this._Section.DataItem.intSectionID, i, AppConfig.GetWebFileType());
                            }
                        }
                        base.GenerateHtmlFile(string.Format("{0}\\{1}", strPath, strFileName), strTmpHtml);
                    }
                }
                else	//无任何文章
                {
                    string strPath = "";

                    if (base.SessionUser.EnableParentPath)
                    {
                        string strParentPath = (this._Section.DataItem.IschvParentPathNull() ? "shtml\\" : (this._Section.DataItem.chvParentPath.Trim() == "" ? "shtml\\" :  (this._Section.DataItem.chvParentPath.Trim() == "/" ?"": this._Section.DataItem.chvParentPath + "\\")));

                        if (SessionUser.WebSiteLevel != 1)
                        {
                            strParentPath = SessionUser.VartualPath + "\\" + strParentPath;
                        }

                        if (!System.IO.Directory.Exists(SessionUser.IssuePath + strParentPath))
                        {
                            System.IO.Directory.CreateDirectory(SessionUser.IssuePath + strParentPath);
                        }

                        strPath = string.Format("{0}{1}{2}.{3}", base.SessionUser.IssuePath + strParentPath, this._Section.DataItem.IschvPageNameNull() ? "T-" + this._Section.DataItem.intSectionID : (string.IsNullOrEmpty(this._Section.DataItem.chvPageName.Trim()) ? "T-" + this._Section.DataItem.intSectionID : this._Section.DataItem.chvPageName), "", AppConfig.GetWebFileType());

                        strHtml = Htmlhandler.HandlerHtmlElementPath(strHtml, base.SessionUser);
                    }
                    else
                    {
                        strPath = string.Format("{0}\\shtml\\T-{1}.{2}", base.SessionUser.IssuePath, this._Section.DataItem.intSectionID, AppConfig.GetWebFileType());
                    }

                    base.GenerateHtmlFile(strPath, strHtml);
                }
            }
        }
        /// <summary>
        /// 获取没有发布的文章ID
        /// </summary>
        /// <param name="IsReIssue">是否重新发布</param>
        /// <returns>文章数量</returns>
        public int GetNoIssueSectionCount(bool IsReIssue)
        {
            StringBuilder strSql = new StringBuilder();
            int intReturn = 0;
            strSql.Append("select * from Article where intArticleID in(");
            strSql.AppendFormat("select intArticleID from ArtSecRelation where intSectionID={0}", this._Section.DataItem.intSectionID);
            strSql.Append(")");
            if (!IsReIssue)
            {
                strSql.AppendFormat(" and intState={0}", (int)Utility.ArticleState.NoIssue);
            }
            using (ArticleFactory objFactory = new ArticleFactory(_DBManager))
            {
                intReturn = objFactory.QueryByCompletionSql(strSql.ToString());
            }
            return intReturn;
        }
    }
}

